;(function (window) {
    var render = function (html, data, scope) {
            var fn = compile.call(window.xtpl, html);
            return fn.apply(window.xtpl, data);
        },
        openTag = "<%",
        closeTag = "%>",
        closeReg = new RegExp(closeTag, "g"),
        rkeyword = /^(break)|(case)|(catch)|(continue)|(default)|(delete)|(do)|(else)|(finally)|(for)|(function)|(if)|(in)|(instanceof)|(new)|(return)|(switch)|(this)|(throw)|(try)|(typeof)|(var)|(void)|(while)|(with)|}|{/,
        compile = function (source) {
            var codeArr = source.replace(/[\r\t\n]/g, "").split(openTag),
                fnBody = " var _ = '',that=$GOLBAL||this,tmp;that['_encodeHTML']=xtpl._encodeHTML;with(that){",
                rpstr;
            for (var i = 0, len = codeArr.length; i < len; i++) {
                var snippet = codeArr[i].trim(),
                    cTagOnEnd = snippet.indexOf(closeTag) === snippet.length - closeTag.length;
                if (!rkeyword.test(snippet)) {
                    if (snippet.indexOf("=") === 0) {
                        fnBody += ";_+=" + snippet.slice(1);
                    } else if (snippet.indexOf(":=") === 0) {
                        rpstr = ";_+=_encodeHTML(tmp);" + (cTagOnEnd ? "" : "_+='");
                        fnBody += "; tmp = " + snippet.slice(2).replace(closeReg, rpstr);
                    } else {
                        fnBody += snippet.indexOf(closeTag) === -1 ? ";_+='" : ";" + snippet;
                    }
                    if (!cTagOnEnd) {
                        fnBody += "';";
                        fnBody = fnBody.replace(closeReg, ";_+='");
                    }else{
                        fnBody = fnBody.replace(closeReg, ";");
                    }
                    
                } else {
                    if (!cTagOnEnd) {
                        fnBody += snippet.replace(closeReg, "_+='") + "';";
                    } else {
                        fnBody += snippet.replace(closeReg, ";");
                    }
                }
            }
            return new Function("$GOLBAL", fnBody + "}; return _;");
        },
        _encodeHTML = function (source) {
            return String(source)
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/\\/g, '&#92;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#39;');
        };
    window.xtpl = {
        render: render,
        compile: compile,
        _encodeHTML : _encodeHTML
    }
})(window);